package controllers

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
	"zbn-oil-consumption/models"
	"zbn-oil-consumption/utils"
)

type Record struct {
}

var mRecord models.Record

func (Record) Save(c *gin.Context) {
	var d models.Record
	if err := c.ShouldBindJSON(&d); err != nil {
		utils.Fail(c, 0, "参数错误")
		return
	}
	userId := c.GetInt64("userId")
	if userId == 0 {
		utils.Fail(c, 0, "请重新登录")
		return
	}
	d.UserId = userId
	d.Username = c.GetString("username")
	if d.Id != nil {
		res, err := mRecord.UpdateById(d)
		if err != nil {
			utils.Fail(c, 0, "")
			return
		}
		utils.Success(c, 200, "", res)
	} else {
		d.CreatedAt = time.Now()
		res, err := mRecord.Add(d)
		if err != nil {
			utils.Fail(c, 0, "")
			return
		}
		utils.Success(c, 200, "", res)
	}
}

// Detail 获取详情
func (Record) Detail(c *gin.Context) {
	idStr, e := c.GetQuery("id")
	if !e {
		utils.Fail(c, 0, "参数错误")
		return
	}
	id, err := utils.StringToObjectID(idStr)
	if err != nil {
		utils.Fail(c, 0, "参数错误")
		return
	}
	res, err := mRecord.FindById(id)
	if err != nil {
		utils.Fail(c, 0, err.Error())
		return
	}
	utils.Success(c, 200, "success", res)
}

// List 获取列表
func (Record) List(c *gin.Context) {
	var params utils.Params
	if err := c.ShouldBind(&params); err != nil {
		utils.Fail(c, 0, "参数错误")
		return
	}
	total, res, err := mRecord.GetList(params)
	if err != nil {
		utils.Fail(c, 0, err.Error())
		return
	}
	utils.SuccessPagination(c, 200, "success", res, total, params.Page, params.PageSize)
}

type Statistics struct {
	List       []models.Record `json:"list"`
	Categories []string        `json:"categories"`
	SeriesData []int64         `json:"seriesData"`
}

// Statistics 获取统计
func (Record) Statistics(c *gin.Context) {
	var d utils.Params
	if err := c.ShouldBind(&d); err != nil {
		utils.Fail(c, 0, "参数错误")
		return
	}
	userId := c.GetInt64("userId")
	if userId == 0 {
		utils.Fail(c, 0, "请重新登录")
		return
	}
	d.UserId = userId
	_, res, err := mRecord.GetListByMonth(d)
	if err != nil {
		utils.Fail(c, 0, err.Error())
		return
	}
	categories := make([]string, 0)
	seriesData := make([]int64, 0)

	t, err := time.Parse("2006-01", d.Month)
	if err != nil {
		utils.Fail(c, 0, err.Error())
		return
	}
	days := time.Date(t.Year(), t.Month()+1, 0, 0, 0, 0, 0, time.UTC).Day()
	for i := 1; i <= days; i++ {
		categories = append(categories, fmt.Sprintf("%d", i))
		var sd int64
		cMonth := d.Month + "-" + utils.PadZeroInt(i)
		for _, re := range res {
			if re.RefuelDate == cMonth {
				sd += re.OilVolume
			}
		}
		seriesData = append(seriesData, sd)

	}
	statistics := Statistics{
		List:       res,
		Categories: categories,
		SeriesData: seriesData,
	}

	utils.Success(c, 200, "", statistics)
}
